import React, { useState } from 'react';
import { Card, List, Badge, Button, Tag, Empty, Tabs, message } from 'antd';
import { BellOutlined, DeleteOutlined, CheckOutlined, SettingOutlined } from '@ant-design/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { authApi } from '@/api/auth';


interface NotificationItem {
  id: string;
  title: string;
  content: string;
  type: 'system' | 'message' | 'alert';
  read: boolean;
  createdAt: string;
}

const NotificationsPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('all');
  const queryClient = useQueryClient();

  // 获取通知列表
  const { data: notificationsData, isLoading } = useQuery({
    queryKey: ['notifications', activeTab],
    queryFn: async () => {
      const params = activeTab === 'unread' ? { read: false } : {};
      const response = await authApi.getNotifications(params);
      return response;
    },
  });

  // 标记通知为已读
  const markAsReadMutation = useMutation({
    mutationFn: authApi.markNotificationAsRead,
    onSuccess: () => {
      message.success('已标记为已读');
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
    },
    onError: () => {
      message.error('操作失败，请重试');
    },
  });

  // 删除所有通知
  const deleteAllMutation = useMutation({
    mutationFn: async () => {
      // 这里需要在 API 中添加批量删除功能
      message.success('所有通知已删除');
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
    },
  });

  // 标记所有为已读
  const markAllReadMutation = useMutation({
    mutationFn: async () => {
      // 这里需要在 API 中添加批量标记已读功能
      message.success('所有通知已标记为已读');
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
    },
  });

  // 处理标记已读
  const handleMarkAsRead = (id: string) => {
    markAsReadMutation.mutate(id);
  };

  // 处理删除所有
  const handleDeleteAll = () => {
    deleteAllMutation.mutate();
  };

  // 处理标记所有已读
  const handleMarkAllRead = () => {
    markAllReadMutation.mutate();
  };

  // 获取通知类型颜色
  const getNotificationColor = (type: string) => {
    switch (type) {
      case 'system':
        return 'blue';
      case 'message':
        return 'green';
      case 'alert':
        return 'red';
      default:
        return 'default';
    }
  };

  // 获取通知类型文本
  const getNotificationTypeText = (type: string) => {
    switch (type) {
      case 'system':
        return '系统通知';
      case 'message':
        return '消息通知';
      case 'alert':
        return '警报通知';
      default:
        return '其他';
    }
  };

  const notifications = notificationsData?.items || [];
  const unreadCount = notificationsData?.unreadCount || 0;

  const filteredNotifications = activeTab === 'unread'
    ? notifications.filter(n => !n.read)
    : notifications;

  return (
    <div style={{ height: '100%', width: '100%' }}>
      <Card
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <BellOutlined />
            消息通知
            {unreadCount > 0 && (
              <Badge count={unreadCount} style={{ backgroundColor: '#ff4d4f' }} />
            )}
          </div>
        }
        style={{ height: '100%' }}
        extra={
          <div style={{ display: 'flex', gap: 8 }}>
            {unreadCount > 0 && (
              <Button
                type="link"
                icon={<CheckOutlined />}
                onClick={handleMarkAllRead}
                loading={markAllReadMutation.isPending}
              >
                全部已读
              </Button>
            )}
            <Button
              type="link"
              icon={<DeleteOutlined />}
              onClick={handleDeleteAll}
              loading={deleteAllMutation.isPending}
            >
              清空全部
            </Button>
            <Button
              type="link"
              icon={<SettingOutlined />}
            >
              通知设置
            </Button>
          </div>
        }
        loading={isLoading}
      >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={[
            {
              key: 'all',
              label: `全部通知`,
              children: null,
            },
            {
              key: 'unread',
              label: (
                <span>
                  未读通知
                  {unreadCount > 0 && (
                    <Badge count={unreadCount} style={{ marginLeft: 4 }} />
                  )}
                </span>
              ),
              children: null,
            },
          ]}
        />

        <List
          itemLayout="horizontal"
          dataSource={filteredNotifications}
          locale={{
            emptyText: <Empty description="暂无通知" />,
          }}
          renderItem={(item: NotificationItem) => (
            <List.Item
              actions={[
                !item.read && (
                  <Button
                    key="read"
                    type="link"
                    size="small"
                    icon={<CheckOutlined />}
                    onClick={() => handleMarkAsRead(item.id)}
                    loading={markAsReadMutation.isPending}
                  >
                    标记已读
                  </Button>
                ),
              ]}
              style={{
                backgroundColor: item.read ? '#fff' : '#f6f6f6',
                borderRadius: 4,
                marginBottom: 8,
                padding: '12px 16px',
              }}
            >
              <List.Item.Meta
                title={
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    {!item.read && (
                      <Badge
                        status="processing"
                        style={{ transform: 'scale(0.8)' }}
                      />
                    )}
                    <span>{item.title}</span>
                    <Tag color={getNotificationColor(item.type)}>
                      {getNotificationTypeText(item.type)}
                    </Tag>
                  </div>
                }
                description={
                  <div>
                    <p style={{ margin: '8px 0', color: '#666' }}>
                      {item.content}
                    </p>
                    <div style={{ fontSize: 12, color: '#999' }}>
                      {new Date(item.createdAt).toLocaleString()}
                    </div>
                  </div>
                }
              />
            </List.Item>
          )}
        />

        {filteredNotifications.length === 0 && (
          <Empty
            description={activeTab === 'unread' ? '暂无未读通知' : '暂无通知'}
            style={{ marginTop: 48 }}
          />
        )}
      </Card>
    </div>
  );
};

export default NotificationsPage;